package com.guosheng.test20181123;

import java.nio.Buffer;
import java.nio.CharBuffer;

public class BufferFillDrain {

    private static void drainBuffer(CharBuffer buffer){
        //buffer.hasRemaining告知在当前位置到限制位置是否还有元素
        System.out.println(buffer.hasRemaining());
        while(buffer.hasRemaining()){
            System.out.print(buffer.get());
        }
        System.out.println(" ");
    }

    private static int index = 0;
    private static String[] strings = {
        "A random string value",
        "The product of an infinite number of monkeys",
        "Hey hey we're the monkees",
        "Opening act for the monkees: Jimi Hendrix",
        "'Scuse me while I kiss this fly",
        "Help Me! Help Me!"
    };

    private static boolean fillBuffer(CharBuffer buffer){
        if(index >= strings.length){
            return false;
        }
        String string = strings[index++];
        for(int i=0;i<string.length();i++){
            buffer.put(string.charAt(i));
        }
        return true;
    }

    public static void main(String[] args){
        CharBuffer charBuffer = CharBuffer.allocate(100);
        while(fillBuffer(charBuffer)){
            charBuffer.flip();//反转此缓冲区，即将上限limit置为position，然后将position置为0，为读缓冲区内容
            drainBuffer(charBuffer);
            charBuffer.clear();//清除此缓冲区，即将limit置为capacity即缓冲区的容量，position置为0
        }
    }
}
